<!-- 
    商品管理功能页面
    添加商品
    使用子组件：富文本组件
    组件名称：RichText
    组件路径：../../../components/richtext/RichText.vue
 -->
<template>
    <div>
        <el-card class="box-card">
            <h4>商品(Spu)介绍</h4>
            <!-- 表单数据 -->
            <div style="margin-top:20px">
                <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" label-width="160px"
                    class="demo-ruleForm">
                    <el-form-item label="商品名称" prop="title" class="is-required">
                        <el-input v-model.trim="ruleForm.title" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="原始价格" prop="originalPrice" class="is-required">
                        <el-input v-model.trim="ruleForm.originalPrice">
                            <template #append>天</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="当前价格" prop="price" class="is-required">
                        <el-input v-model.trim="ruleForm.price">
                            <template #append>天</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="VIP价格" prop="vipPrice" class="is-required">
                        <el-input v-model.trim="ruleForm.vipPrice">
                            <template #append>天</template>
                        </el-input>
                    </el-form-item>
                    <el-form-item label="剩余库存">
                        <el-input type="password" autocomplete="off" disabled />
                    </el-form-item>
                    <el-form-item label="运费模板">
                        <el-select placeholder="请选择" v-model="ruleForm.freightTemplateId">
                            <template v-for="item in freightList" :key="freightList">
                                <el-option :label="item.title" :value='item.id' />
                            </template>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="是否在售" class="is-required">
                        <el-radio-group v-model="ruleForm.status">
                            <el-radio :label="1">在售</el-radio>
                            <el-radio :label="0">下架</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="商品图片">
                        <template #default="scope">
                            <el-upload v-model:file-list="fileList" :headers="headers"  :action="action.url"
                                :before-upload="beforeAvatarUpload" list-type="picture-card" :before-remove="beforeRemove"
                                :on-success="handleImgSuccess" :on-preview="handlePictureCardPreview" >
                                <el-icon>
                                    <Plus />
                                </el-icon>
                            </el-upload>
                            <!-- 查看图片对话框 -->
                            <el-dialog v-model="uploadDialogVisible">
                                <img style="width:100%" w-full :src="dialogImageUrl" alt="Preview Image" />
                            </el-dialog>
                        </template>
                    </el-form-item>
                    <el-form-item label="商品单位" prop="unit" class="is-required">
                        <el-input v-model.trim="ruleForm.unit" autocomplete="off" placeholder="件 / 个 / 盒" />
                    </el-form-item>
                    <el-form-item label="所属类目">
                        <el-cascader :options="cascaderCategory" :props="categoryProps" v-model="ruleForm.categoryId" />
                    </el-form-item>
                    <el-form-item label="商品简介">
                        <el-input v-model.trim="ruleForm.description" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="商品详细介绍" prop="richText"  class="is-required">
                        <!-- 富文本组件 -->
                        <div style="width:100%">
                            <RichText ref="editor" v-model="formState.contents" @getContent="getContent" />
                        </div>
                    </el-form-item>
                </el-form>
            </div>
        </el-card>
        <el-card class="box-card">
            <div class="card-header">
                <h5>商品参数</h5>
                <el-button type="primary" plain @click="handlerAddGoodsParameter">添加</el-button>
            </div>
            <div>
                <el-table :data="ruleForm.attributeList">
                    <el-table-column prop="attribute" label="商品参数名称" />
                    <el-table-column prop="value" label="商品参数值" />
                    <el-table-column label="操作" width="100px" align="center">
                        <template #default="scope" v-if="ruleForm.attributeList.length != 0">
                            <el-button type="danger" @click="handlerDeletegoods(scope.$index)">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-card>
        <el-card class="box-card">
            <div class="card-header">
                <h5>规格维度</h5>
                <el-button type="primary" plain @click="handlerAddSpecsDimension">添加</el-button>
            </div>
            <div>
                <el-table :data="ruleForm.specificationList">
                    <el-table-column label="维度ID" />
                    <el-table-column prop="title" label="维度名称" />
                    <el-table-column label="创建时间" align="center">
                        <template #default="scope">
                            <span v-if="scope.row.gmtCreate">
                                {{new Date(scope.row.gmtCreate).friendlyTime(1)}}
                            </span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="160px" align="center">
                        <template #default="scope" v-if="ruleForm.specificationList.length != 0">
                            <el-button type="primary" @click="handlerEditgoods(scope.row.title,scope.$index)">修改
                            </el-button>
                            <el-button type="danger" @click="handlerDeletespeci(scope.$index)">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-card>
        <el-card class="box-card">
            <template #header>
                <div class="card-header">
                    <h4>商品(Sku)详情</h4>
                    <el-button type="primary" plain @click="handlerBatchPricing">批量定价</el-button>
                    <div style="margin-top:10px" v-for="(iten,index) in ruleForm.specificationList">
                        <el-tag type="warning" style="margin-right:10px">{{iten.title}}</el-tag>
                        <el-tag v-for="tag in iten.values" :key="tag" class="mx-1" closable style="margin-right:10px"
                            :disable-transitions="false" @close="handleClose(tag,index)">
                            {{ tag }}
                        </el-tag>
                        <el-input v-if="inputVisible && refButtonInd == index" ref="InputRef" v-model="inputValue"
                            class="ml-1 w-20" style="width:80px;margin-right: 10px;" size="small"
                            @keyup.enter="handleInputConfirm(index)" @blur="handleInputConfirm(index)" />
                        <el-button v-if="ruleForm.specificationList.length" class="button-new-tag ml-1" size="small"
                            @click="showInput(index)">
                            + 添加
                        </el-button>
                    </div>
                </div>
            </template>
            <div>
                <el-table :data="ruleForm.skuList" :span-method="objectSpanMethod" border>
                    <el-table-column v-for="(item, index) in ruleForm.specificationList.filter(v=>v.values.length)" :prop="'id_' + item.title"
                        :label="item.title" />
                    <el-table-column prop="skuId" label="SkuID" />
                    <el-table-column label="￥价格(元)" width="180px">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.originalPrice" :min="1" />
                        </template>
                    </el-table-column>
                    <el-table-column label="￥VIP(元)" width="180px">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.vipPrice" :min="1" />
                        </template>
                    </el-table-column>
                    <el-table-column label="￥吊牌价(元)" width="180px">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.price" :min="1" />
                        </template>
                    </el-table-column>
                    <el-table-column label="库存(件)" width="180px">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.stock" :min="1" />
                        </template>
                    </el-table-column>
                    <el-table-column label="重量(克)" width="180px">
                        <template #default="scope">
                            <el-input-number v-model="scope.row.weight" :min="1" />
                        </template>
                    </el-table-column>
                    <el-table-column label="Sku图片" align="center">
                        <template #default="scope">
                            <!-- 开发时使用 action="/upload/admin" -->
                            <el-upload style="width:100%;text-align: center;" :headers="headers" :action="action.url"
                                :show-file-list="false" :on-success="handleAvatarSuccess"
                                @click="handlerGetIndex(scope.$index)">
                                <img style="width:40px;height:40px" v-if="scope.row.img" :src="scope.row.img" />
                                <el-icon v-else size="30px">
                                    <Upload />
                                </el-icon>
                            </el-upload>
                        </template>
                    </el-table-column>
                    <el-table-column label="条形码" width="200px">
                        <template #default="scope">
                            <el-input v-model="scope.row.barCode">
                                <template #append>
                                    <span @click="scope.row.barCode = +new Date()">随机数</span>
                                </template>
                            </el-input>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
        </el-card>
        <!-- 页尾按钮 -->
        <div class="footerButton">
            <el-button @click="closeAddPage">关闭</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">保存商品</el-button>
        </div>
        <!-- 对话框 -->
        <el-dialog v-model="dialogVisible" :title="refTitle" width="50%">
            <el-form ref="refParamsRules" :model="parameterTypeData" status-icon :rules="paramsRules"
                class="demo-ruleForm">
                <!-- 创建规格 -->
                <template v-if="refNum=='0'">
                    <el-form-item label="商品参数名称" prop="title" class="is-required" label-width="140px"
                        style="padding-right:50px">
                        <el-input v-model.trim="parameterTypeData.title" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="商品参数值" prop="labal" class="is-required" label-width="140px"
                        style="padding-right:50px">
                        <el-input v-model.trim="parameterTypeData.labal" autocomplete="off" />
                    </el-form-item>
                </template>
                <template v-if="refNum=='1'||refNum=='3'">
                    <el-form-item label="类型名称" prop="typeTitle" class="is-required" label-width="140px"
                        style="padding-right:50px">
                        <el-input v-model.trim="parameterTypeData.typeTitle" autocomplete="off" 
                        @keypress.enter.prevent="handlerFixSubmit(refParamsRules)"/>
                    </el-form-item>
                </template>
                <!-- 批量定价 -->
                <template v-if="refNum=='2'">
                    <el-form-item label="现价(￥)" label-width="140px" style="padding-right:50px">
                        <el-input-number v-model="batchPricing.price" :min="1" />
                    </el-form-item>
                    <el-form-item label="VIP价格(￥)" label-width="140px" style="padding-right:50px">
                        <el-input-number v-model="batchPricing.vipPrice" :min="1" />
                    </el-form-item>
                    <el-form-item label="吊牌价(￥)" label-width="140px" style="padding-right:50px">
                        <el-input-number v-model="batchPricing.originalPrice" :min="1" />
                    </el-form-item>
                </template>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handlerFixSubmit(refParamsRules)">{{refButton}}</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup>
import { ClassGoodsadd } from '#/index';
import { reactive, ref, nextTick } from 'vue'
import { ElMessage, ElMessageBox, ElInput, type FormInstance, type UploadProps, type UploadUserFile } from 'element-plus'
import { Upload, Plus } from '@element-plus/icons-vue';
import { post } from "@/utils/index";
import router from "@/router";
import RichText from "../../../components/richtext/RichText.vue";
import cookie from "js-cookie"
// 获取请求头
const headers = reactive({
    AdminToken: cookie.get("token")
})

const action = reactive({
    url:process.env.NODE_ENV === 'development'?'/upload/admin':'http://zxwyit.cn:8989/upload/admin'
})
const ruleFormRef = ref<FormInstance>()
const refParamsRules = ref<FormInstance>()
const dialogImageUrl = ref('')
// 上传图片对话框放大
const uploadDialogVisible = ref(false)
// 商品参数\规格维度对话框显示隐藏
const dialogVisible = ref(false)
const refTitle = ref("创建规格")
const refButton = ref('创建')
/**
 * 用于判断对话框显示隐藏
 * 0：设置商品参数
 * 1：创建规格
 * 2：批量定价
 * 3: 修改规格
 */
const refNum = ref('0')
// 存储多个图片的数组
const fileList = ref<UploadUserFile[]>([])
/**
 * 存储类目树数据
 */
const cascaderCategory: Array<object> = reactive([])
/**
 * 存储类目树数据，规定子节点数据
 */
const categoryProps = reactive({
    emitPath: false,//返回数字类型数据，true返回数组类型数据
    children: 'childrenList',
    value: 'id',
    label: 'title',
})
// 表单数据
const ruleForm = reactive(new ClassGoodsadd())
// 获取规格维度当前行下标
const refTableInd = ref()
// 标签输入框类型
const inputValue = ref('')
// 标签输入框显示隐藏
const inputVisible = ref(false)
// 获取标签输入框实例
const InputRef = ref<InstanceType<typeof ElInput> | []>([])
// 获取标签页的输入框的当前下标
const refButtonInd = ref<number | ''>('')
// 用于存储商品(Sku)详情的长度
const skuLength = ref()
// 对话框数据
const parameterTypeData = reactive({
    title: '',
    labal: '',
    typeTitle: '',
})
// 存储sku表格下标
const ind = ref()
// 批量定价
const batchPricing = reactive({
    originalPrice: '',   //现价
    vipPrice: '',    //VIP价格
    price: ''    //吊牌价
})
// 获取的数据
const formState = reactive({ contents: '' })
// 获取内容，子传父数据
const getContent = (v: string) => {
    formState.contents = v
    console.log(formState.contents);
}

/**
 * 表单验证
 */
//原始价格
function valoriginalPrice(rule: Object, value: string | number, callback: Function) {
    if (value === '') {
        callback(new Error("请输入原始价格"))
    } else if (value === 0) {
        callback(new Error("请规定价格"))
    } else if (ruleForm.originalPrice < ruleForm.price) {
        callback(new Error("原始价格不能小于当前价"))
    } else {
        callback()
    }
}
//当前价格
function valPrice(rule: Object, value: string | number, callback: Function) {
    if (value === '') {
        callback(new Error("请输入当前价格"))
    } else if (value === 0) {
        callback(new Error("请规定价格"))
    } else if (ruleForm.price < ruleForm.vipPrice) {
        callback(new Error("当前价格不能小于VIP价"))
    } else {
        callback()
    }
}
//vip价格
function valvipPrice(rule: Object, value: string | number, callback: Function) {
    if (value === '') {
        callback(new Error("请输入vip价格"))
    } else if (value === 0) {
        callback(new Error("请规定价格"))
    } else if (ruleForm.vipPrice > ruleForm.price) {
        callback(new Error("VIP价不能大于当前价"))
    } else {
        callback()
    }
}
//运费模板
function valfreightTemplateId(rule: Object, value: string | number, callback: Function) {
    if (value === '') {
        callback(new Error("请选择运费模板"))
    } else {
        callback()
    }
}
//图片
function valimg(rule: Object, value: string | number, callback: Function) {
    if (value === '') {
        callback(new Error("请上传图片"))
    } else {
        callback()
    }
}
//单位
function unit(rule: Object, value: string | number, callback: Function) {
    if (value === '') {
        callback(new Error("请选择单位"))
    } else {
        callback()
    }
}
// 商品详细介绍
function valoriginalrichText(rule: Object, value: string | number, callback: Function) {
    if (formState.contents === '') {
        callback(new Error("请填写商品详细介绍"))
    } else {
        callback()
    }
}
//验证规则
const rules = reactive({
    title: [{ required: true, message: '商品名称不能为空', trigger: 'blur' }],             //名称
    originalPrice: [{ validator: valoriginalPrice, trigger: 'blur' },],                 //原始价格
    price: [{ validator: valPrice, trigger: 'blur' }],                                    //当前价格
    vipPrice: [{ validator: valvipPrice, trigger: 'blur' }],                              //vip价格
    freightTemplateId: [{ validator: valfreightTemplateId, trigger: 'change' }],            //运费模板
    img: [{ validator: valimg, trigger: 'blur' }],                                        //图片
    unit: [{ validator: unit, trigger: 'blur' },],                                     //单位
    richText:[{ validator: valoriginalrichText, trigger: 'blur' }],                     //商品详细介绍
})
//商品参数验证规则
const paramsRules = reactive({
    title: [{ required: true, message: '请输入商品参数名称', trigger: 'blur' }],
    labal: [{ required: true, message: '请输入商品参数值', trigger: 'blur' },],
    //规格维度验证规则
    typeTitle: [{ required: true, message: '请输入类型名称', trigger: 'blur' }],
})
// 确认按钮
const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            // 获取富文本的数据
            ruleForm.detail = formState.contents
            console.log(ruleForm);
            let data = {
                _gp: 'admin.product',
                _mt: 'create',
                spuDTO: JSON.stringify({ ...ruleForm })
            }
            // 提交请求
            post(data).then((res) => {
                if (200 === res.errno) {
                    ElMessageBox.confirm(
                        '是否跳转到商品页面?',
                        '添加成功',
                        { confirmButtonText: '确定', cancelButtonText: '取消', type: 'success', }
                    ).then(() => {
                        router.replace({ name: 'Commodi' })
                        ElMessage.success("您已回到商品页面")
                    }).catch(() => {
                        ElMessage.warning("已取消")
                    })
                } else {
                    ElMessage.error(res.errmsg)
                }
            })
        } else {
            ElMessage.warning("请先填好数据，在进行提交！")
            return false
        }
    })
}
// 维度名称表格
function lang() {
    //过滤掉商品维度数据里面的children数组
    let valueList = ruleForm.specificationList.filter((item) => item.values.length).map((item) => item.values);
    const typeSku = ruleForm.specificationList.filter((item) => item.values.length).map(item => item.title)//获取到商品维度数组里面所有的title（维度名称）
    // 使用笛卡尔积算法将数据进行交叉处理
    // 数组[11,12][21,22]变成[11,21],[11,22],[12,21],[12,22]
    let arr = valueList.reduce(
        (total:string[][], current) => {
            let temp: string[][] = []
            total.forEach(item => {
                current.forEach(value => {//拿到skuTagsList数组里面的每个维度名称
                    temp.push(item.concat([value]))//将其链接
                })
            })
            return temp
        },
        [[]]
    )
    // 判断arr的属性是否存在数据，如果没有最直接返回
    for (let i = 0; i < arr.length; i++) {
        if(arr[i].length === 0) return []
    }
    if(!ruleForm.specificationList[0].values?.length) return []
    // 进行拼接数据
    let list = arr.map(item => {
        let obj = { specification: '' }
        item.forEach((val, index: number) => {
            // 相当于是添加一个对象
            obj['id_' + typeSku[index]] = val
            obj['title'] = item.join(',')
            obj.specification += ruleForm.specificationList[index].title + '_' + val + ','
            if (index === item.length - 1) {
                obj.specification = obj.specification.slice(0, -1)
            }
        })
        return obj
    })
    //生成的数组长度赋值给skuLength，即表格要生成的行数
    skuLength.value = list.length
    ruleForm.skuList.length = 0
    Object.assign(ruleForm.skuList, list)
}
/**
 * 表格合并
*/
const objectSpanMethod = ({
    rowIndex,   // sku表行的下标
    columnIndex, // sku表列的下标
}: SpanMethodProps) => {
    if (ruleForm.specificationList.length == 0) {
        return
    }
    // 对specificationList进行过滤，只返回大于0的数据
    let newFormSkuList = ruleForm.specificationList.filter(v => v.values.length > 0)
    // 获取sku表格总长度
    let rowspan = ruleForm.skuList.length
    // 使用循环获取过滤出来的数组下标
    for (let index = 0; index < newFormSkuList.length; index++) {
        // 使用sku表总长度 除等 values的长度，获取需要跨多少行数字
        rowspan /= newFormSkuList[index].values.length
        // 进行判断列的下标是否全等于我们循环出来的下标 
        if (columnIndex === index) {
            // 行的下标取余sku表的总长度全等于0
            //每次跨行的数量相同,所以当前行索引号%跨行数量==0就是要跨行的开始
            if (rowIndex % rowspan === 0) { 
                return { rowspan: rowspan, colspan: 1 }
            } else {
                return { rowspan: 0, colspan: 0 }
            }
        }
    }
    //拿到第一列要合并的行数
    // let typeSkuList = ruleForm.specificationList.filter((item) => item.values.length)
    // let rowspan = skuLength.value / typeSkuList[0].values.length
    // for (let index = 0; index < typeSkuList.length; index++) {
    //     if (index !== 0) {
    //         //依次拿到每一列要合并的行数
    //         rowspan = rowspan / typeSkuList[index].values.length;
    //     }
    //     if (columnIndex === index) {
    //         //当条件成立时，即合并行数
    //         if (rowIndex % rowspan === 0) {
    //             return {
    //                 //合并的行数配置
    //                 rowspan: rowspan,
    //                 colspan: 1
    //             };
    //         } else {
    //             return {
    //                 rowspan: 0,
    //                 colspan: 0
    //             };
    //         }
    //     }
    // }
}
/**
 * 获取sku表格下标
 * @param index 
 */
function handlerGetIndex(index: number) {
    ind.value = index
}
// 表格上传图片
const handleAvatarSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    ruleForm.skuList[ind.value].img = response.url
}
// 删除标签
const handleClose = (tag: string, index: number) => {
    ruleForm.specificationList[index].values.splice(ruleForm.specificationList[index].values.indexOf(tag), 1)
    if(ruleForm.specificationList[0].values.length != 0){
        lang()
    }else{
        ruleForm.skuList.length = 0
    }
    
}
// 显示隐藏输入框
const showInput = (index: number) => {
    refButtonInd.value = index
    inputVisible.value = true
    nextTick(() => {
        InputRef.value[0]!.input!.focus()
    })
}
// 添加标签
const handleInputConfirm = (index: number) => {
    if (inputValue.value) {
        let refBool = false //定义一个判断值，用于判断是否已经存在该标签，有为true,没有为false
        if (ruleForm.specificationList[index].values.length > 0) {
            // 使用some来遍历对象，是否存在一样的标签，有为true,没有为false
            refBool = ruleForm.specificationList[index].values.some(item => item == inputValue.value)
        }
        if (refBool) {
            ElMessage.warning("已存在该标签")
        } else {
            ruleForm.specificationList[index].values.push(inputValue.value)
            lang()
        }
    }
    inputVisible.value = false
    inputValue.value = ''
}
/**
* 获取类目树数据
*/
function getCategory() {
    let data = {
        _gp: 'admin.category',
        _mt: 'categoryTree'
    }
    post(data).then((res) => {
        if (200 === res.errno) {
            cascaderCategory.length = 0
            cascaderCategory.push(...res.data)
        }
    })
}
//获取运费模板
let freightList: { title: string, id: number }[] = reactive([])
getFreightList()
function getFreightList() {
    if (freightList.length > 0) { return }
    post({ _gp: 'admin.freight', _mt: 'list' }).then((res) => {
        console.log(res);
        if (200 == res.errno) {
            freightList.length = 0;
            freightList.push(...res.data)
        }
    }).catch((err) => {
        console.log(err);
    });
}
// 如果已经请求了那么就不用重复请求
if (cascaderCategory.length <= 0) {
    getCategory()//获取类目树数据
}

// 退出按钮
const closeAddPage = () => {
    router.push({
        path: '/index/cmmodity/commodi'
    })
}
// 上传图片前的回调函数
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
    console.log(fileList.value);
    if (fileList.value.length > 4) {
        ElMessage.error('添加的图片不能大于5张')
        return false
    }
    return true
}
//移除图片前 对editform 图片列表同步处理
const beforeRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
    let index = fileList.value.findIndex(item => item.uid === uploadFile.uid)
    ruleForm.imgList.splice(index, 1)
    if (index === 0) {
        ruleForm.img = ruleForm.imgList[0]
    }
    return true
}
// 上传图片成功的回调函数
const handleImgSuccess: UploadProps['onSuccess'] = (response, uploadFile) => {
    ruleForm.img = response.url
    ruleForm.imgList.push(response.url)
}
// 点击图片放大
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = uploadFile.url!
    uploadDialogVisible.value = true
}
// 商品参数添加
function handlerAddGoodsParameter() {
    refNum.value = '0'
    refTitle.value = "设置商品参数"
    refButton.value = "确定"
    dialogVisible.value = true
}
// 规格维度添加
function handlerAddSpecsDimension() {
    parameterTypeData.typeTitle = ''
    refNum.value = '1'
    refTitle.value = "创建规格"
    refButton.value = "创建规格"
    dialogVisible.value = true
}
/**
 * 规格维度修改
 * @param row   获取到规格维度title
 * @param index 获取规格维度当前行下标
 */
function handlerEditgoods(row: string, index: number) {
    refTableInd.value = index
    parameterTypeData.typeTitle = row
    refNum.value = '3'
    refTitle.value = "修改规格维度"
    refButton.value = "确定"
    dialogVisible.value = true
}
// 批量定价
function handlerBatchPricing() {
    refNum.value = '2'
    refTitle.value = "批量定价"
    refButton.value = "确定"
    dialogVisible.value = true
}
// 批量定价赋值给水库表格
function resure() {
    if (batchPricing.vipPrice < batchPricing.price && batchPricing.price < batchPricing.originalPrice) {
        ruleForm.skuList.map(v => Object.assign(v, { price: batchPricing.price, vipPrice: batchPricing.vipPrice, originalPrice: batchPricing.originalPrice }))
    } else {
        return ElMessage.warning('批量定价vip价格必须小于现价并且vip价格小于原价并且现价小于原价!')
    }
    dialogVisible.value = false
}
// 对话框确定按钮
function handlerFixSubmit(formEl: FormInstance | undefined) {
    if (!formEl) return
    formEl.validate((valid) => {
        if (valid) {
            switch (refNum.value) {
                case '0':
                    if (ruleForm.attributeList.some(item => item.attribute === parameterTypeData.title)) {
                        ElMessage.warning("商品参数名称不能重复")
                        return
                    }
                    // 使用push插入数据
                    ruleForm.attributeList.push({ attribute: parameterTypeData.title, value: parameterTypeData.labal })
                    parameterTypeData.title = ''
                    parameterTypeData.labal = ''
                    // 隐藏对话框
                    dialogVisible.value = false
                    break;
                case '1':
                    if (ruleForm.specificationList.some(item => item.title === parameterTypeData.typeTitle)) {
                        ElMessage.warning("规格维度名称不能重复")
                        return
                    }
                    let data = {
                        title: parameterTypeData.typeTitle,
                        gmtCreate: +new Date(),
                        gmtUpdate: +new Date(),
                        inputSkuTagVisible: false,
                        inputSkuTagValue: '',
                        values: []
                    }
                    // 使用push插入数据
                    ruleForm.specificationList.push(data)
                    lang() //调用sku表格数据
                    parameterTypeData.typeTitle = ''
                    break;
                case '2':
                    // 调用赋值函数
                    resure()
                    break;
                case '3':
                    // 修改规格维度
                    ruleForm.specificationList[refTableInd.value].title = parameterTypeData.typeTitle
                    parameterTypeData.typeTitle = ''
                    dialogVisible.value = false
                    break;
                default:
                    break;
            }
        } else {
            return false
        }
    })
}
/**
 * 删除商品参数
 * @param index   获取到删除规定值
 */
function handlerDeletegoods(index: number) {
    ruleForm.attributeList.splice(index, 1)
}
/**
 * 删除规格维度
 * @param index   获取到删除规定值
 */
function handlerDeletespeci(index: number) {
    ruleForm.specificationList.splice(index, 1)
    if (0 === ruleForm.specificationList.length) {
        ruleForm.skuList.length = 0
    }else{
        lang()
    }
}
</script>

<style lang="less" scoped>
// 卡片布局样式，间距调整
.card-header {
    line-height: 30px;
}

.box-card {
    margin: 0px 20px;
    box-sizing: border-box;
}

.box-card:nth-child(1) {
    margin-top: 20px;
}

// 页尾按钮样式
.footerButton {
    height: 60px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
    margin-right: 20px;
}

:deep .el-input-group__append {
    width: 60px;
    cursor: pointer;
}
</style>